<template>
  <PageLayout title="管理员面板" description="系统管理和用户权限控制">
    <template #header>
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-text-primary">管理员面板</h1>
          <p class="text-text-secondary mt-1">系统管理和用户权限控制</p>
        </div>
        <div class="flex items-center gap-2">
          <span class="text-sm text-text-secondary">当前角色：</span>
          <UiBadge :variant="roleBadgeVariant" size="sm">{{ getRoleDisplayName(currentUserRole) }}</UiBadge>
        </div>
      </div>
    </template>

    <div v-if="!canViewAdminPanel" class="text-center py-12">
      <div class="text-6xl mb-4">🔒</div>
      <h2 class="text-xl font-semibold text-text-primary mb-2">访问被拒绝</h2>
      <p class="text-text-secondary">您没有权限访问管理员面板</p>
    </div>

    <div v-else class="space-y-6">
      <UiTabGroup v-model="activeTab" ref="tabsRef" :tabs="tabs" />
      <div v-if="isTabLoading" class="py-8 flex justify-center"><LoadingSpinner /></div>

      <!-- 概览 -->
      <div class="space-y-6" v-show="activeTab === 'overview' && !isTabLoading">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div class="card">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-sm text-text-secondary">总用户数</p>
                <p class="text-2xl font-bold text-text-primary">{{ stats?.total_users || 0 }}</p>
              </div>
              <div class="text-3xl">👥</div>
            </div>
          </div>

          <div class="card">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-sm text-text-secondary">总电影数</p>
                <p class="text-2xl font-bold text-text-primary">{{ stats?.total_movies || 0 }}</p>
              </div>
              <div class="text-3xl">🎬</div>
            </div>
          </div>

          <div class="card">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-sm text-text-secondary">总评论数</p>
                <p class="text-2xl font-bold text-text-primary">{{ stats?.total_comments || 0 }}</p>
              </div>
              <div class="text-3xl">💬</div>
            </div>
          </div>

          <div class="card">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-sm text-text-secondary">管理员</p>
                <p class="text-2xl font-bold text-text-primary">{{ stats?.users_by_role?.admin || 0 }}</p>
              </div>
              <div class="text-3xl">👑</div>
            </div>
          </div>
        </div>

        <div class="card">
          <div class="flex items-center justify-between mb-2">
            <h3 class="text-lg font-semibold text-text-primary">最近7天活动</h3>
          </div>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="text-center">
              <p class="text-2xl font-bold text-blue-500">{{ stats?.recent_activity?.new_users || 0 }}</p>
              <p class="text-sm text-text-secondary">新用户</p>
            </div>
            <div class="text-center">
              <p class="text-2xl font-bold text-green-500">{{ stats?.recent_activity?.new_movies || 0 }}</p>
              <p class="text-sm text-text-secondary">新电影</p>
            </div>
            <div class="text-center">
              <p class="text-2xl font-bold text-purple-500">{{ stats?.recent_activity?.new_comments || 0 }}</p>
              <p class="text-sm text-text-secondary">新评论</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户管理 -->
      <div v-if="canManageUsers" class="card" v-show="activeTab === 'users' && !isTabLoading">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-text-primary">用户管理</h3>
          <div class="flex items-center gap-2">
            <UiInput v-model="userSearch" placeholder="搜索用户..." class="w-48" />
            <UiButton @click="refreshUsers" :disabled="loading" variant="secondary" size="sm">
              {{ loading ? '加载中...' : '刷新' }}
            </UiButton>
          </div>
        </div>

        <div v-if="error" class="mb-4 p-3 bg-red-50 border border-red-200 rounded text-red-600">
          {{ error }}
        </div>

        <div v-if="pagedUsers.length === 0" class="text-center py-8 text-text-secondary">暂无用户数据</div>

        <div v-else class="space-y-4">
          <div v-for="user in pagedUsers" :key="user.id" class="flex items-center justify-between p-4 bg-background-800 rounded-xl border border-background-700">
            <div class="flex items-center gap-3">
              <UiAvatar :src="user.avatar" :name="user.name" size="md" />
              <div>
                <p class="font-medium text-text-primary">{{ user.name }}</p>
                <p class="text-sm text-text-secondary">{{ user.bio || '暂无简介' }}</p>
                <p class="text-xs text-text-secondary">上传: {{ user.uploads }} | 关注者: {{ user.followers }} | {{ user.isAi ? 'AI用户' : '普通用户' }}</p>
              </div>
            </div>

            <div class="flex items-center gap-3">
              <UiBadge :variant="getRoleBadgeVariant(user.role)" size="sm">{{ getRoleDisplayName(user.role) }}</UiBadge>
              <UiSelect 
                v-model="userRoleChanges[user.id]" 
                @change="handleRoleChange(user.id, $event)"
                :disabled="user.id === currentUserId"
                class="w-32"
              >
                <option value="user">普通用户</option>
                <option value="moderator">版主</option>
                <option value="admin">管理员</option>
              </UiSelect>
            </div>
          </div>

          <div class="flex items-center justify-between pt-2">
            <div class="text-sm text-text-secondary">第 {{ userPage }} / {{ totalUserPages }} 页，共 {{ filteredUsers.length }} 人</div>
            <div class="flex items-center gap-2">
              <UiButton size="sm" variant="secondary" :disabled="userPage<=1" @click="userPage--">上一页</UiButton>
              <UiButton size="sm" variant="secondary" :disabled="userPage>=totalUserPages" @click="userPage++">下一页</UiButton>
            </div>
          </div>
        </div>
      </div>

      <!-- 权限变更日志 -->
      <div v-if="canManageUsers" class="card" v-show="activeTab === 'logs' && !isTabLoading">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-text-primary">权限变更日志</h3>
          <UiButton size="sm" variant="secondary" :disabled="loadingMoreLogs" @click="loadMoreLogs">{{ loadingMoreLogs ? '加载中...' : '加载更多' }}</UiButton>
        </div>

        <div v-if="roleLogs.length === 0" class="text-center py-8 text-text-secondary">暂无权限变更记录</div>

        <div v-else class="space-y-3">
          <div v-for="log in roleLogs" :key="log.id" class="flex items-center justify-between p-3 bg-background-800 rounded-xl border border-background-700">
            <div>
              <p class="text-sm text-text-primary">
                <span class="font-medium">用户 {{ log.user_id }}</span>
                <span class="mx-2">从</span>
                <UiBadge size="sm" :variant="getRoleBadgeVariant(log.old_role || 'user')">{{ getRoleDisplayName(log.old_role || 'user') }}</UiBadge>
                <span class="mx-2">变更为</span>
                <UiBadge size="sm" :variant="getRoleBadgeVariant(log.new_role)">{{ getRoleDisplayName(log.new_role) }}</UiBadge>
              </p>
              <p v-if="log.reason" class="text-xs text-text-secondary mt-1">原因: {{ log.reason }}</p>
              <p class="text-xs text-text-secondary">{{ formatDate(log.changed_at) }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 标签管理 -->
      <div v-if="canManageUsers && activeTab === 'tags'">
        <TagManagementPanel />
      </div>
    </div>
  </PageLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import PageLayout from '../components/layout/PageLayout.vue'
import { UiButton, UiSelect, UiBadge, UiTabGroup, UiInput, LoadingSpinner, UiAvatar } from '../components/ui'
import TagManagementPanel from '../components/tags/TagManagementPanel.vue'

import { useUserStore } from '../store/useUserStore'
import { useUiStore } from '../store/useUiStore'
import type { UserRole, UserWithRole, RoleChangeLog } from '../types/admin'

const userStore = useUserStore()
const { userId } = storeToRefs(userStore)

const {
  adminLoading: loading,
  adminError: error,
  currentUserRole,
  canManageUsers,
  canViewAdminPanel
} = storeToRefs(userStore)
const {
  checkUserRole,
  getAllUsersWithRoles,
  setUserRole,
  getRoleChangeLogs,
  getAdminStats
} = userStore

const users = ref<UserWithRole[]>([])
const roleLogs = ref<RoleChangeLog[]>([])
const stats = ref<any>(null)
const userRoleChanges = ref<Record<string, UserRole>>({})

const currentUserId = computed(() => userId.value)

// 获取角色显示名称
const getRoleDisplayName = (role: UserRole): string => {
  const roleNames = {
    user: '普通用户',
    moderator: '版主',
    admin: '管理员'
  }
  return roleNames[role] || '未知'
}

// 使用统一的 UiBadge 变体
const getRoleBadgeVariant = (role: UserRole): 'secondary' | 'info' | 'destructive' => {
  const variants = {
    user: 'secondary',
    moderator: 'info',
    admin: 'destructive'
  } as const
  return variants[role] || 'secondary'
}
const roleBadgeVariant = computed(() => getRoleBadgeVariant(currentUserRole.value))

// 处理角色变更
const handleRoleChange = async (userId: string, newRole: UserRole) => {
  try {
    const result = await setUserRole({
      target_user_id: userId,
      new_role: newRole,
      reason: '管理员手动调整'
    })

    if (result.success) {
      // 更新本地用户列表
      const userIndex = users.value.findIndex(u => u.id === userId)
      if (userIndex !== -1) {
        users.value[userIndex].role = newRole
      }
      
      // 刷新日志
      await loadRoleLogs()
      
      console.log('角色更新成功:', result.message)
    } else {
      console.error('角色更新失败:', result.error)
    }
  } catch (err) {
    console.error('处理角色变更失败:', err)
  }
}

// 刷新用户列表（首次加载 + 手动刷新）
const refreshUsers = async () => {
  const userList = await getAllUsersWithRoles()
  users.value = userList
  usersLoaded.value = true
  userPage.value = 1
  // 初始化角色变更映射
  userList.forEach(user => {
    userRoleChanges.value[user.id] = user.role
  })
}

// 加载权限变更日志（默认20条，可增量加载）
const logsLimit = ref(20)
const loadingMoreLogs = ref(false)
const loadRoleLogs = async () => {
  const logs = await getRoleChangeLogs(logsLimit.value)
  roleLogs.value = logs
  logsLoaded.value = true
}
const loadMoreLogs = async () => {
  loadingMoreLogs.value = true
  logsLimit.value += 20
  await loadRoleLogs()
  loadingMoreLogs.value = false
}

// 加载统计信息
const loadStats = async () => {
  const adminStats = await getAdminStats()
  stats.value = adminStats
  statsLoaded.value = true
}

// 格式化日期
const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 懒加载：按标签页分别加载
const tabs = [
  { id: 'overview', label: '概览' },
  { id: 'users', label: '用户管理' },
  { id: 'logs', label: '权限变更日志' },
  { id: 'tags', label: '标签管理' },
]
const tabsRef = ref<any>(null)
const activeTab = ref<string>('overview')
const statsLoaded = ref(false)
const usersLoaded = ref(false)
const logsLoaded = ref(false)
  
  // 统一的 Tab 加载状态：当前激活 Tab 对应数据未加载则显示全局 Loading
  const isTabLoading = computed(() => {
    if (activeTab.value === 'overview') return !statsLoaded.value && loading.value
    if (activeTab.value === 'users') return canManageUsers.value && !usersLoaded.value && loading.value
    if (activeTab.value === 'logs') return canManageUsers.value && !logsLoaded.value && loading.value
    return false
  })

const ensureLoadForTab = async (tabId: string) => {
  if (!canViewAdminPanel.value) return
  if (tabId === 'overview' && !statsLoaded.value) await loadStats()
  if (tabId === 'users' && canManageUsers.value && !usersLoaded.value) await refreshUsers()
  if (tabId === 'logs' && canManageUsers.value && !logsLoaded.value) await loadRoleLogs()
}

onMounted(async () => {
  // 等待认证状态初始化完成
  if (userStore.loading) {
    await new Promise<void>((resolve) => {
      const unwatch = watch(() => userStore.loading, (newLoading: boolean) => {
        if (!newLoading) { unwatch(); resolve() }
      })
    })
  }
  if (!userStore.isAuthenticated) return
  await checkUserRole()
  if (!canViewAdminPanel.value) return

  // 初次仅加载当前激活标签页数据（默认概览）
  activeTab.value = tabsRef.value?.activeTab || activeTab.value || 'overview'
  await ensureLoadForTab(activeTab.value)

  // 监听标签切换，按需加载（v-model 已同步，这里仅确保懒加载）
  watch(activeTab, async (val) => {
    if (!val) return
    await ensureLoadForTab(val)
  })
})

// 用户分页与搜索（前端渲染分页，避免一次性渲染过多DOM）
const userSearch = ref('')
const userPage = ref(1)
const userPageSize = ref(20)
const uiStore = useUiStore()
const filteredUsers = computed(() => {
  const keyword = userSearch.value.trim().toLowerCase()
  let list = users.value
  if (uiStore.filterAiContent) {
    list = list.filter(u => !u.isAi)
  }
  if (!keyword) return list
  return list.filter(u =>
    u.name?.toLowerCase().includes(keyword) ||
    u.bio?.toLowerCase().includes(keyword)
  )
})
const totalUserPages = computed(() => Math.max(1, Math.ceil(filteredUsers.value.length / userPageSize.value)))
watch([filteredUsers, userPageSize], () => { userPage.value = 1 })
const pagedUsers = computed(() => {
  const start = (userPage.value - 1) * userPageSize.value
  return filteredUsers.value.slice(start, start + userPageSize.value)
})
</script>
